package detect;

import interfaces.Detect;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import entities.AnalyticTechnology;
import entities.Domain;

public class DetectAnalyticYandexMetrika implements Detect {
	@SuppressWarnings("serial")
	@Override
	public void getInfo(Map<String, Object> obj) {
		// TODO Auto-generated method stub
		Document doc = (Document) obj.get("doc");
		Domain domain = (Domain) obj.get("domain");

		Type listType = new TypeToken<List<AnalyticTechnology>>() {
		}.getType();
		List<AnalyticTechnology> analytics = new Gson().fromJson(
				domain.getAnalyticTechnology(), listType);

		if (analytics == null) {
			analytics = new ArrayList<AnalyticTechnology>();
		}

		try {
			AnalyticTechnology analytic = new AnalyticTechnology();

			Elements listJs = doc.select("script");
			String name = "";
			for (Element js : listJs) {
				if (js.attr("src").toLowerCase().contains("mc.yandex.ru")
						|| js.html().toLowerCase().contains("mc.yandex.ru")) {
					name = "Yandex Metrika";
					analytic.setN(name);

					break;
				}
			}

			if (!name.isEmpty()) {
				analytics.add(analytic);
			}

			domain.setAnalyticTechnology(new Gson().toJson(analytics));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
